<style scoped>
.dialog-footer button:first-child {
  margin-right: 10px;
}

input {
  padding: 0 0 0 1px;
  width: 70%;
  margin-left: 10px;
}

textarea {
  width: 70%;
  height: 70px;
  margin-left: 10px;
  padding: 1px 0 0 2px;
}
</style>

<template>
  <!-- border: 1px solid blue -->
  <div style=" padding: 10px;height: 75vh;width: 100%;box-sizing: border-box">

    <!-- 搜索区域 -->
    <div style="margin: 0 0 10px 1px">
      <el-input @keyup="Load" v-model="data.SearchKeyWord" maxlength="30" placeholder="请输入关键字（仅文件名和文件类型可查）"
                style="width: 23%"
                clearable></el-input>
<!--      <el-button @click="Load" type="primary" style="margin-left: 10px">查询</el-button>-->
      <el-button
          type="danger"
          style="margin-left: 10px"
          @click="handleBatchDelete"
          :disabled="data.selectedRows.length === 0">
        批量删除记录
      </el-button>
    </div>

    <!--  表格  -->
    <!-- header-cell-style设置头部居中；cell-style设置单元格内容居中;stripe斑马纹 -->
    <!--  sortable实现排序按钮  -->
    <el-table
        :data="data.tableData"
        :header-cell-style="{ 'text-align': 'center' }"
        :cell-style="{ 'text-align': 'center' }"
        border
        stripe
        style="width: 98%; border-radius: 5px;margin-left: 1%"
        @selection-change="handleSelectionChange"
    >
      <el-table-column fixed type="selection" sortable prop="fileId" width="100" label="文件ID"/>
      <el-table-column sortable width="180" label="文件名">
        <template #default="scope">
          <el-tooltip v-if="scope.row.fileType === 'doc' || scope.row.fileType === 'docx'" content="点击编辑文件内容"
                      effect="light" :show-after="300">
            <el-link style="cursor: pointer" @click="handleFileClick(scope.row.filePath)" :underline="false">
              {{ scope.row.fileName }}
            </el-link>
          </el-tooltip>
          <span v-else>{{ scope.row.fileName }}</span>
        </template>
      </el-table-column>
      <el-table-column sortable prop="filePath" width="280" label="文件下载地址"/>
      <el-table-column sortable prop="fileType" width="120" label="文件类型"/>
      <el-table-column sortable width="150" label="是否文件夹">
        <template #default="scope">
          <span>{{ scope.row.isFolder == 0 ? "否" : "是" }}</span>
        </template>
      </el-table-column>
      <el-table-column sortable prop="size" width="180" label="文件大小(kb)"/>
      <el-table-column sortable prop="parentFolderId" width="150" label="所属文件夹ID"/>
      <el-table-column sortable prop="rootFolderId" width="150" label="根文件夹ID"/>
      <el-table-column sortable prop="uploaderId" width="120" label="上传者ID"/>
      <el-table-column sortable prop="uploaderUserName" width="180" label="上传者用户名"/>
      <el-table-column sortable prop="uploadTime" width="280" label="上传时间"/>
      <el-table-column sortable prop="lastModifiedTime" width="280" label="更新时间"/>
      <el-table-column sortable width="180" label="状态" min-width="100">
        <template #default="scope">
          <span :style="scope.row.isDeleted !== 0 ? { color: 'red'} : {}">
            {{ scope.row.isDeleted === 0 ? '正常' : '已移入回收站' }}
          </span>
        </template>
      </el-table-column>
      <el-table-column sortable fixed="right" label="操作" min-width="230">
        <template #default="scope">
          <el-popconfirm title="确定永久删除吗?" v-model="scope.visible" @confirm="handleDelete(scope.row.fileId)">
            <template v-slot:reference>
              <el-button type="primary" link :icon="Delete">删除该记录</el-button>
            </template>
          </el-popconfirm>
          <el-popconfirm  v-if="scope.row.isDeleted == 0" title="确定移入回收站吗?" v-model="scope.visible" @confirm="Recycle(scope.row.fileId)">
            <template v-slot:reference>
              <el-button type="primary" link :icon="Brush">移入回收站</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <!--  分页  -->
    <el-pagination
        v-model:current-page="data.currentPage"
        v-model:page-size="data.pageSize"
        :page-sizes="[5, 10, 15, 20]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="data.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        style="margin-top: 1%"
    ></el-pagination>
  </div>

  <div style="height: 8vh;">

  </div>
</template>

<script setup>
import {reactive, ref,} from "vue";
import {Brush, Delete, Edit} from '@element-plus/icons-vue'
import request from "../utils/request.js";
import {ElLoading, ElMessage, ElMessageBox} from 'element-plus';
import {mainStore} from "@/stores/main.js";
import {useRouter} from "vue-router";

const Store = mainStore();
const router = useRouter();

const fileTableFormRef = ref();
const data = reactive({
  //弹窗默认关闭
  centerDialogVisible: false,
  //当前页
  currentPage: 1,
  //每页多少条数据
  pageSize: 5,
  //搜索输入框
  SearchKeyWord: "",
  //数据条数
  total: 0,
  //表格数据
  tableData: [],
  selectedRows: [], // 选中行的数组
});

const Load = () => {
  let loadingInstance = ElLoading.service({fullscreen: true}); // 启动全屏加载动画
  console.log("搜索框关键词：", data.SearchKeyWord);

  request.get(`/java/file/getAllFiles?current=${data.currentPage}&size=${data.pageSize}&SearchKeyWord=${data.SearchKeyWord}`)
      .then((response) => {
        console.log("文件管理数据：", response);
        data.tableData = response.data.records;
        data.total = response.data.total;
      })
      .catch((error) => {
        console.error('请求发生错误:', error);
      })
      .finally(() => {
        loadingInstance.close();
      });
};

Load()

//改变分页大小
const handleSizeChange = (pageSize) => {
  data.currentPage = 1
  data.pageSize = pageSize
  Load()
}

//去到第几页
const handleCurrentChange = (currentPage) => {
  data.currentPage = currentPage
  Load()
}

//删除
const handleDelete = async (fileId) => {

  try {
    const res = await request.delete("/java/file/deleteById/" + fileId);
    console.log(res);
  } catch (e) {
    console.log(e);
  }

  handleCurrentChange(1);
};


//移入回收站
const Recycle = (fileId) => {
  request.delete(`/disk/delete?fileId=${fileId}`).then((res) => {
    console.log("打印res:", res);
    if (res.code === 200) {
      ElMessage.success(res.data)
      Load();
    } else {
      ElMessage.error(res.data)
      Load();
    }
  })
}

const handleSelectionChange = (selected) => {
  data.selectedRows = selected;
};

const handleBatchDelete = async () => {
  const selectedIds = data.selectedRows.map(row => row.fileId);
  if (selectedIds.length === 0) {
    console.warn('没有选中任何行');
    return;
  }
  console.log('选中的行ID：', selectedIds);

  // 确认是否删除
  const confirmDelete = await ElMessageBox.confirm(
      '确定永久删除选中的文件吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  );

  if (confirmDelete) {
    // 执行批量删除操作
    try {
      const res = await request.delete('/java/file/delete/' + selectedIds);
      console.log('批量删除返回信息：', res);
      // 成功后刷新列表
      Load();
    } catch (error) {
      console.error('批量删除失败：', error);
    }
  }
};

const handleFileClick = (filePath) => {
  console.log("filePath:" + filePath);
  // 编码您要传递的路径
  const path = encodeURIComponent(filePath);
  // 拼接URL和参数
  const url = `showDoc?filePath=${path}`;
  // 使用JavaScript的window.open方法打开新窗口
  // 第一个参数是要打开的文件路径，第二个参数是窗口名，第三个参数是窗口特性
  // 打开POBrowser窗口，并确保宽度和高度没有'px'后缀
  POBrowser.openWindow(url, '', 'width=1150,height=900');
}
</script>
